// rem移动窗口自适应
(function(doc, win) {
	showData();
    var docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange': 'resize',
    recalc = function() {
        var clientWidth = docEl.clientWidth;
        if (!clientWidth) return;
        document.getElementById('root').style.height = window.innerHeight + 'px';
    };

    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

function showData() {
	var _html = '';
	$.each(jsonData, function(idx, obj) {
        _html += html.replace('selected', idx == 0 ? 'item_selected' : '')
        			 .replace('-ckb-', obj.id + '-ckb-' + idx)
        			 .replace('item-', 'item-' + idx)
        			 .replace('title', (idx + 1) + '. ' + obj.title)
        			 .replace('showDate', obj.showDate);
        if (idx == 0) $('.ant-input').val(obj.text);
	});
	$('.history_list').html(_html);
}

function showTableData(json) {
	//console.log('json', json);
	if (json.result == undefined || json.result == null || json.result == '') {
		alert('识别失败，请重新上传！');
		return;
	}
	// 添加到前面
	tableData.unshift(json.result.result_data);
	var _html = '';
	$.each(tableData, function(idx, url) {
		var fileName = url.substring(url.lastIndexOf('/') + 1, url.indexOf('.xls'));
			fileName = fileName.length > 15 ? fileName.substring(0, 15) : fileName;
        _html += t_html.replace('selected', idx == 0 ? 'item_selected' : '')
        			   .replace('item-', 'item-' + idx)
        			   .replace('download_url', (idx + 1) + '. ' + fileName + '.xls');
        if (idx == 0) $('.ant-input').val(url);
	});
	$('.history_list').html(_html);
}

function copyText() {
	var txt = $('.ant-input').val();
	if (txt == '') return;
	document.getElementById('text_area').select(); // 选择对象
	document.execCommand("Copy"); // 执行浏览器复制命令
	alert("已复制好，可贴粘。");
}

function getFileUrl(sourceId) {
    var url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    return url;
}

function preImg(sourceId, targetId) {
    var url = getFileUrl(sourceId);
    var imgPre = document.getElementById(targetId);
    imgPre.src = url;
}

$('#preImgDiv').click(function() {
    preImg('file', 'bigImage');
    $('#bigImageDiv').show();
});

$('.ant-modal-close').click(function() {
    $('#bigImageDiv').hide();
});

$('#copyText').click(function() {
	copyText();
});

// 复选框事件
$('input[type=checkbox]').click(function() {
	var obj = $(this);
	obj.checked = !obj.checked;
});

// 全选/反选
$('.select_btn').click(function() {
	var ckbs = $("input:checkbox");
	var ckbs_ = $("input:checkbox:checked");
	$.each($("input[type=checkbox]"), function(i) {
		var obj = $(this)[0];
		obj.checked = ckbs.size() > ckbs_.size() ? true : false;
    });
});

// 列表项选中
$('.history_list').on('click', '.item', function(e) {
	var item_id = e.currentTarget.id.split('-')[1];
	var item_size = $('.item').size();
	var ocrType = $('#ocrType').val();
	
	for (var i = 0; i < item_size; i++) {
		if (item_id == i) {
			$('#item-' + i).addClass('item_selected');
			if (ocrType == 'TABLE') {
				$('.ant-input').val(tableData[i]);
				location.href = tableData[i];
			} else {
				// val()可取到初始值与修改后的值，text()不可
				$('.ant-input').val(jsonData[i].text);
			}
		} else {
			$('#item-' + i).removeClass('item_selected');
		}
	}
});

$('.download_btn').click(function() {
	var txt_ids = selectIds().txt_ids;
	if (txt_ids == '') {
		alert('请至少勾选一项！');
		return;
	}
	location.href = path + "/wx/download/" + txt_ids;
});

// 删除
$('.delete_btn').click(function() {
	var obj = selectIds();
	$.each(obj.item_ids, function(idx, id) {
		jsonData.splice(id == 0 ? 0 : id - 1, 1);
	});
	if (obj.txt_ids == '') {
		alert('请至少勾选一项！');
		return;
	}
	$.ajax({
        url: path + "/wx/delete?ids=" + obj.txt_ids + "&uid=" + $('input[name=uid]').val(),
        dataType: "JSON",
        type: "DELETE",
        success: function(data) {
            if (data.success) {
            	alert('操作成功！');
            	showData(jsonData);
            } else {
            	alert('操作失败，请刷新页面重试！');
            }
        }
    });
});

function selectIds() {
	var txt_ids = [], item_ids = [], object = {};
	$.each($("input:checkbox:checked"), function(i) {
		var obj = $(this)[0];
		var txtid = obj.id.split('-')[0];
		var ckbid = obj.id.split('-')[2];
		if (obj.checked) {
			txt_ids.push(txtid);
			item_ids.push(parseInt(ckbid));
		}
    });
	object.item_ids = item_ids;
	object.txt_ids = txt_ids.toString();
	return object;
}

function uploadImage() {
    var flag = checkImage();
    if (!flag) return;
    if ($('input[name=uid]').val() == '') {
    	location.href = path + '/wx/' + tag;
    	return;
    }
    $('#loading').show();
    $('#preImgDiv').show();
    preImg('file', 'smallImg');
    // 请求接口
    var ocrType = $('#ocrType').val();
    var url = path + (ocrType == 'TABLE' ? '/table/ocr' : '/webUpload');
    $.ajax({
        url: url,
        type: 'POST',
        cache: false,
        data: new FormData($('#form')[0]),
        timeout: 90000,
        //必须false才会避开jQuery对 formdata 的默认处理 
        // XMLHttpRequest会对 formdata 进行正确的处理
        processData: false,
        //必须false才会自动加上正确的Content-Type 
        contentType: false,
        xhrFields: { withCredentials: true },
        success: function(json) {
            $('#loading').hide();
            if (!json.success) {
            	alert(json.result);
            	return;
            }
            if (ocrType == 'TABLE') {
            	showTableData(json);
            	return;
            }
            if (json.useCount == 0 && vip == 0) {
            	alert('次数用完啦，请在小程序充值使用哦！');
            	return;
            }
            $('.ant-input').val(json.text);
            var str = '剩余次数：' + json.useCount + '次';
            if (vip > 0) {
            	str = vip == 1 ? 'VIP永久会员' : '包年会员';
            }
            $('.money_left').html(str);
            // 添加到前面
            jsonData.unshift(json);
            // 加载数据
            showData(jsonData);
        },
        error: function(XMLHttpRequest, status, error) {
            console.log('error', error);
        },
        complete: function(res) {
        	$('#loading').hide();
            console.log('complete', res);
        }
    });
}

function checkImage() {
    var animateimg = $("#file").val(); //获取上传的图片名 带//
    var imgarr = animateimg.split('\\'); //分割
    var myimg = imgarr[imgarr.length - 1]; //去掉 // 获取图片名
    var houzui = myimg.lastIndexOf('.'); //获取 . 出现的位置
    var ext = myimg.substring(houzui, myimg.length).toUpperCase(); //切割 . 获取文件后缀
    var file = $('#file').get(0).files[0]; //获取上传的文件
    var fileSize = file.size; //获取上传的文件大小
    var maxSize = 5242880; //最大5MB
    if (ext != '.PNG' && ext != '.JPG' 
    	&& ext != '.JPEG' && ext != '.BMP' 
    	&& ext != '.WEBP' && ext != '.GIF') {
        alert('文件类型错误，请上传图片！');
        return false;
    }
    if (parseInt(fileSize) >= parseInt(maxSize)) {
        alert('上传的文件不能超过5MB！');
        return false;
    }
    return true;
}
